package com.sc.sc250601.cook.handler;


import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.sc.sc250601.cook.pojo.Notification;
import com.sc.sc250601.cook.util.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SocketIOHandler {
    // 存储用户ID与Socket会话ID的映射（关键：必须是Spring管理的单例）
    private static final Map<Long, String> USER_SOCKET_MAP = new ConcurrentHashMap<>();

    // 构造方法添加日志，确认Spring是否实例化了该类
    public SocketIOHandler() {
        System.out.println("SocketIOHandler被Spring实例化了！");
    }

//    @Autowired
//    private SocketIOServer server; // 由Spring注入的Socket服务实例


    // 客户端连接时记录映射关系
    @OnConnect
    public void onConnect(SocketIOClient client) {

        // 最优先的日志：只要进入该方法就打印，排除后续逻辑干扰
        System.out.println("检测到客户端连接！会话ID：" + client.getSessionId());

        // 从连接参数中获取userId
        String userIdStr = client.getHandshakeData().getSingleUrlParam("userId");
        if (userIdStr != null && !userIdStr.isEmpty()) {
            try {
                Long userId = Long.parseLong(userIdStr);
                // 存储用户ID与会话ID的映射
                USER_SOCKET_MAP.put(userId, client.getSessionId().toString());
                System.out.println("用户[" + userId + "]已连接，会话ID：" + client.getSessionId());


            } catch (NumberFormatException e) {
                System.err.println("无效的userId格式：" + userIdStr);
            }
        } else {
            System.err.println("连接失败：未传递userId参数");
        }
    }


    // 推送消息给指定用户

    public void pushToUser(Long userId, Object message) {
        // 动态获取SocketIOServer实例，避免直接依赖
        SocketIOServer server = SpringContextUtil.getBean(SocketIOServer.class);

        // 后续发送消息的逻辑...
        String sessionId = USER_SOCKET_MAP.get(userId);
        if (sessionId != null) {
            SocketIOClient client = server.getClient(UUID.fromString(sessionId));

            // 3. 发送消息（确保事件名与前端一致，这里用"message"）
            try {
                client.sendEvent("message", message); // 事件名必须与前端监听的一致
                System.out.println("成功推送消息给用户[" + userId + "]：" + message);

            } catch (Exception e) {
                System.err.println("推送消息时发生异常：" + e.getMessage());
                e.printStackTrace();
            }
            if (client != null) {
                client.sendEvent("newNotification", message);
            }

        }



    }


    // 批量推送（调用上面的单用户推送）
    public void pushToUsers(Iterable<Long> userIds, Object message) {
        userIds.forEach(userId -> pushToUser(userId, message));
    }


    // 客户端断开连接时清理映射
    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String userIdStr = client.getHandshakeData().getSingleUrlParam("userId");
        if (userIdStr != null) {
            try {
                Long userId = Long.parseLong(userIdStr);
                USER_SOCKET_MAP.remove(userId);
                System.out.println("用户[" + userId + "]已断开连接，移除映射");
            } catch (NumberFormatException e) {
                // 忽略无效格式
            }
        }
    }
}
